package cn.shyouchi.wuguanjia.android.ui.event.arrange;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.event.PersonRankEvent;
import cn.shyouchi.wuguanjia.android.ui.event.labor.LaborRequestEntity;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import rx.Observable;
import rx.Observer;

public class EventArrangeActivity extends BaseActivity implements EventArrangeContract.View {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.rv_arrange)
    RecyclerView mRvArrange;
    @BindView(R.id.btn_add_arrange)
    Button mBtnAddArrange;
    @BindView(R.id.btnPri)
    Button btnPri;
    @BindView(R.id.btnNext)
    Button btnNext;
    @BindView(R.id.tv_date)
    TextView tv_date;

    ArrangePresenter mArrangePresenter;
    String projectId;
    Calendar mCalendar;
    ArrangeDateAdapter mArrangeDateAdapter;
    List<LaborRequestEntity.ResultMessageBean> dates = new ArrayList<>();
    List<PersonRankAdapter> personRankAdapters = new ArrayList<>();
    ArrangeFragment mArrangeFragment;


    @Override
    public int initContentView() {
        return R.layout.activity_event_arrange;
    }

    @Override
    public void initInjector() {
        mArrangePresenter = new ArrangePresenter(mContext, this);
        projectId = getIntent().getStringExtra("projectId");
        mCalendar = Calendar.getInstance();
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        mTopBar.setTitle(getTitle().toString());
        setSupportActionBar(mTopBar.getToolbar());
        EventBus.getDefault().register(this);
        mArrangeFragment = (ArrangeFragment) getSupportFragmentManager().findFragmentById(R.id.fgm_rank);
        mArrangeDateAdapter = new ArrangeDateAdapter(dates, this);
        mRvArrange.setAdapter(mArrangeDateAdapter);
        mRvArrange.setLayoutManager(new LinearLayoutManager(mContext));

        onDateChange();


        btnPri.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//
                mCalendar.add(Calendar.MONTH, -1);
                onDateChange();

            }
        });
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mArrangePresenter.getschedulingList(projectId,new SimpleDateFormat("yyyy-MM-dd").format(mCalendar.getTime()));
                mCalendar.add(Calendar.MONTH, 1);
                onDateChange();
            }
        });

    }


    public void onDateChange() {
        tv_date.setText(new SimpleDateFormat("yyyy年MM月").format(mCalendar.getTime()));
        mArrangePresenter.getArrangeList(projectId, mCalendar.getTime());
//        mArrangePresenter.getPers；onHours(projectId, new SimpleDateFormat("yyyy-MM-dd").format(mCalendar.getTime()));
//        mArrangePresenter.getschedulingList(projectId,new SimpleDateFormat("yyyy-MM-dd").format(mCalendar.getTime()));
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @OnClick(R.id.btn_add_arrange)
    public void onClick() {
        startActivity(new Intent(mContext, AddArrangeActivity.class));
    }


    @Override
    public void onDataRefresh(List<LaborRequestEntity.ResultMessageBean> resultMessageBeen) {
        dates.clear();
        dates.addAll(resultMessageBeen);
        mArrangeDateAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPersonRankRefresh(List<PersonRankAdapter> personRankAdapters) {
        this.personRankAdapters.clear();
        this.personRankAdapters.addAll(personRankAdapters);

        LogUtil.json(personRankAdapters);
    }

    @Override
    public void onItemClick(LaborRequestEntity.ResultMessageBean entity) {
        mArrangeFragment.setRankData(entity);
    }

    @Override
    public void onRemoteArrangeChange(final List<RemoteArrangeEntity.ResultMessageBean> remoteArrange) {
        LogUtil.json(remoteArrange);
        Observable.from(remoteArrange).subscribe(new Observer<RemoteArrangeEntity.ResultMessageBean>() {
            @Override
            public void onCompleted() {
                mArrangeFragment.refreshList();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(RemoteArrangeEntity.ResultMessageBean msgBean) {

                for (LaborRequestEntity.ResultMessageBean date : dates) {
                    if (date.getDate().equals(msgBean.getDay())) {
                        for (RemoteArrangeEntity.ResultMessageBean.ServiceBean s : msgBean.getService()) {
                            for (LaborRequestEntity.ResultMessageBean.ServiceBeanX sx : date.getService()) {
                                if (sx.getService().getId() == s.getId()) {
                                    for (RemoteArrangeEntity.ResultMessageBean.ServiceBean.UserBean userBean : s.getUser()) {
                                        PersonRankAdapter.Person person = new PersonRankAdapter.Person(userBean.getUser_id(), userBean.getName(),userBean.getLine());
                                        person.setTag(sx);
                                        sx.addSubItem(person);
//                                        sx.setService_people(sx.getService_people() - 1);
                                        for (PersonRankAdapter p : personRankAdapters) {
                                            if (p.getPerson().getUser_id() == userBean.getUser_id()) {

                                                for (PersonRankAdapter.Rank r : p.getRanks()) {
                                                    if (r.getRank_id() == s.getId()) {
                                                        r.setRank_count(r.getRank_count() - 1);
                                                        break;
                                                    }
                                                }
                                                break;
                                            }

                                        }

                                    }
                                    break;
                                }
                            }
                        }
                        break;
                    }
                }


            }
        });


    }

    @Override
    public void onDelClick() {

    }

    @Override
    public boolean isSave() {
        return mArrangeFragment.isSave;
    }

    @Override
    public void showAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("警告");
        builder.setMessage("本排班尚未保存，请点击保存!");
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mArrangeFragment.saveDate();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

    public List<PersonRankAdapter> getPersonRankAdapters() {
        return personRankAdapters;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPersonRankChange(PersonRankEvent event) {
        for (PersonRankAdapter adapter : personRankAdapters) {
            if (adapter.getPerson().getUser_id() == event.getPerson().getUser_id()) {
                for (PersonRankAdapter.Rank r : adapter.getRanks()) {
                    if (r.getRank_id() == event.getRank()) {
                        if (event.getType() == PersonRankEvent.CHANGE_TYPE_ADD) {
                            r.setRank_count(r.getRank_count() + 1);
                        } else {
                            r.setRank_count(r.getRank_count() - 1);
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Override
    public void onBackPressed() {
        if (!isSave()) {
            showAlert();
        } else {
            super.onBackPressed();
        }
    }


    public String getProjectId() {
        return projectId;
    }

}
